package com.ultrapower.ctool.xn_app;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hh.timeselector.timeutil.datedialog.DateListener;
import com.hh.timeselector.timeutil.datedialog.TimeConfig;
import com.hh.timeselector.timeutil.datedialog.TimeSelectorDialog;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.http.BaseActivity;
import com.ultrapower.ctool.model.ReWangGeFVO;
import com.ultrapower.ctool.model.RegisterRolePirVO;

import org.json.JSONArray;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddWangGeHandleActivity extends BaseActivity implements View.OnClickListener {

    public AutoCompleteTextView bh_add_wghandle;//编号
    private TextView time_add_wghandle;//处理时间
    private ImageView time_img_add_wghandle;
    private EditText result_add_wghandle;
    private CustomApplication application;
    private Button save_add_wghandle;//保存
    private Button cancle_add_wghandle;//取消
    public String data;
    private Gson gson = new Gson();
    public List<ReWangGeFVO> suggest;
    public ArrayAdapter<ReWangGeFVO> aAdapter;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    //Intent intent1 = getIntent();
                    Toast.makeText(getApplicationContext(), "添加成功", Toast.LENGTH_SHORT).show();
                    // TODO: 2017/5/21 null修改
                   // Intent intent = new Intent(AddWangGeHandleActivity.this, WangGeHandleActivity.class);
                   // intent.putExtra("query_sid",intent1.getStringExtra("query_sid"));
                   // startActivity(intent);
                    finish();
                    break;
                case 0:
                    Toast.makeText(getApplicationContext(), "系统出现异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_wang_ge_handle);
        application = (CustomApplication) getApplication();

        init();
    }

    protected void init() {
        bh_add_wghandle = (AutoCompleteTextView) findViewById(R.id.bh_add_wghandle);
        time_add_wghandle = (TextView) findViewById(R.id.time_add_wghandle);
        time_img_add_wghandle = (ImageView) findViewById(R.id.time_img_add_wghandle);
        result_add_wghandle = (EditText) findViewById(R.id.result_add_wghandle);
        save_add_wghandle = (Button) findViewById(R.id.save_add_wghandle);
        cancle_add_wghandle = (Button) findViewById(R.id.cancle_add_wghandle);
        time_img_add_wghandle.setOnClickListener(this);
        save_add_wghandle.setOnClickListener(this);
        cancle_add_wghandle.setOnClickListener(this);
        suggest = new ArrayList<ReWangGeFVO>();
        bh_add_wghandle.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable editable) {

            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String newText = s.toString();
                new AddWangGeHandleActivity.getJson().execute(newText);
            }

        });

    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.time_img_add_wghandle:
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String date = sdf.format(new Date());
                showDatePickDialog(TimeConfig.YEAR_MONTH_DAY_HOUR_MINUTE, date);
                break;
            case R.id.save_add_wghandle:
                //String dwidStr = ((RegisterRolePirVO) userroleSpinner.getSelectedItem()).getId();
                String cltime = time_add_wghandle.getText().toString();
               // String clresult = result_add_wghandle.getText().toString();
                //System.out.println(suggest);
                if (suggest.size()<1
                        || "".equals(cltime)
                       ) {
                    Toast.makeText(getApplicationContext(), "请填写完整信息", Toast.LENGTH_SHORT).show();
                } else {
                    final Map<String, String> map = new HashMap<String, String>();
                    map.put("cldwid", suggest.get(0).getId());
                    map.put("cltime", time_add_wghandle.getText().toString().trim() + ":00");
                    map.put("clresult", result_add_wghandle.getText().toString().trim());
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            Response enttyperesponse = null;
                            try {
                                OkHttpClient client = new OkHttpClient();
                                FormBody.Builder builder = new FormBody.Builder()
                                        .add("userId", String.valueOf(application.getLoginUser().getLogin_id()));
                                for (Map.Entry<String, String> m : map.entrySet()) {
                                    builder.add(m.getKey(), m.getValue());
                                }
                                RequestBody resultRequestBody = builder.build();
                                Request enttypeRequest = new Request.Builder().url(ConfUtils.SERVICE_URL + "form/doAdd/c_aj_sjcl").post(resultRequestBody).build();
                                enttyperesponse = client.newCall(enttypeRequest).execute();
                                if (enttyperesponse.isSuccessful()) {
                                    String result = enttyperesponse.body().string();
                                    Map<String, Object> resultMap = gson.fromJson(result, Map.class);
                                    System.out.println(resultMap);
                                    if ((boolean) resultMap.get("success")) {
                                        Message message = new Message();
                                        message.what = 1;
                                        handler.sendMessage(message);
                                    } else {
                                        Message message = new Message();
                                        message.what = 0;
                                        handler.sendMessage(message);
                                    }
                                }
                            } catch (Exception e) {
                                Message message = new Message();
                                message.what = 0;
                                handler.sendMessage(message);
                                e.printStackTrace();
                            } finally {
                                if (enttyperesponse != null) enttyperesponse.close();
                            }
                        }
                    }).start();
                }
                break;
            case R.id.cancle_add_wghandle:
                finish();
                break;
        }
    }

    private void showDatePickDialog(int type, String date) {
        TimeSelectorDialog dialog = new TimeSelectorDialog(this);
        //设置标题
        dialog.setTimeTitle("选择时间:");
        //显示类型
        dialog.setIsShowtype(TimeConfig.YEAR_MONTH_DAY_HOUR_MINUTE);
        //默认时间
        dialog.setCurrentDate(date);
        //隐藏清除按钮
        dialog.setEmptyIsShow(false);
        dialog.setDateListener(new DateListener() {
            @Override
            public void onReturnDate(String time, int year, int month, int day, int hour, int minute, int isShowType) {
                time_add_wghandle.setText(time);
            }

            @Override
            public void onReturnDate(String empty) {
                time_add_wghandle.setText(empty);
            }
        });
        dialog.show();
    }


    class getJson extends AsyncTask<String, String, String> {
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            aAdapter = new ArrayAdapter<ReWangGeFVO>(getApplicationContext(), R.layout.simple_dropdown_item_1line, suggest);
            bh_add_wghandle.setThreshold(1);
            bh_add_wghandle.setAdapter(aAdapter);
            aAdapter.notifyDataSetChanged();
        }

        @Override
        protected String doInBackground(String... key) {
            suggest.clear();
            Response response = null;
            if (key.length != 0 && !"".equals(key[0])) {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("field", "cldwid")
                            .add("code", "c_aj_sjcl")
                            .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                            .add("like", key.length == 0 ? "" : key[0])
                            .build();
                    Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/findLikeJson").post(requestBody).build();
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        suggest = gson.fromJson(result, new TypeToken<List<ReWangGeFVO>>() {}.getType());
                        System.out.println(suggest);
                    }
                } catch (Exception e) {
                    Log.w("Error", e.getMessage());
                }
            }
            return null;
        }

    }
}
